package cn.signalpha.modules.auth.endpoint;

import cn.signalpha.common.cache.CacheNames;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.cache.utils.CacheUtil;
import cn.signalpha.core.jwt.JwtUtil;
import cn.signalpha.core.jwt.props.JwtProperties;
import cn.signalpha.core.launch.constant.TokenConstant;
import cn.signalpha.core.redis.cache.RedisCache;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.secure.utils.AuthUtil;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.constant.SystemConstant;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.WebUtil;
import cn.signalpha.modules.auth.dto.UserInfo;
import cn.signalpha.modules.auth.provider.ITokenGranter;
import cn.signalpha.modules.auth.provider.TokenGranterBuilder;
import cn.signalpha.modules.auth.provider.TokenParameter;
import cn.signalpha.modules.auth.utils.TokenUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.UUID;

import static cn.signalpha.core.cache.constant.CacheConstant.*;

/**
 * 令牌端点
 */
@ApiSort(1)
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "用户授权认证", tags = "授权接口")
public class TokenEndPoint {

	private final RedisCache redisCache;
	private final JwtProperties jwtProperties;

	@RequestMapping(value = "/oauth/token", method = {RequestMethod.GET, RequestMethod.POST})
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取认证令牌", notes = "https://www.yuque.com/docs/share/9494f920-693a-4dcb-bd91-70ed5d6d391f?#（密码：gwrv） 《登陆流程文档》")
	public R token(@ApiParam(value = "账号") @RequestParam(required = false) String username,
				   @ApiParam(value = "密码") @RequestParam(required = false) String password) {

		String grantType = WebUtil.getRequest().getParameter("grant_type");
		String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

		String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs().set("username", username).set("password", password).set("grantType", grantType).set("refreshToken", refreshToken).set("userType", userType);

		ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		if (userInfo == null || userInfo.getId() == null) {
			return R.fail(TokenUtil.USER_NOT_FOUND);
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return R.fail(TokenUtil.USER_HAS_NO_ROLE);
		}

		return R.data(TokenUtil.createAuthInfo(userInfo));
	}

	@GetMapping("/oauth/captcha")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "获取验证码")
	public R captcha() {
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
		String verCode = specCaptcha.text().toLowerCase();
		String key = UUID.randomUUID().toString();
		redisCache.setEx(CacheNames.CAPTCHA_KEY + key, verCode, Duration.ofMinutes(30));
		return R.data(Kv.create().set("key", key).set("image", specCaptcha.toBase64()));
	}

	@GetMapping("/oauth/logout")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "退出登录")
	public R logout() {
		TokenUser user = AuthUtil.getUser();
		if (user != null && jwtProperties.getState()) {
			String token = JwtUtil.getToken(WebUtil.getRequest().getHeader(TokenConstant.HEADER));
			JwtUtil.removeAccessToken(user.getTenantId(), user.getClientId(), String.valueOf(user.getUserId()), token);
		}
		return R.success(SystemConstant.DEFAULT_SUCCESS_MESSAGE);
	}

	@GetMapping("/oauth/clear-cache")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "清除缓存")
	public R clearCache() {
		CacheUtil.clear(BIZ_CACHE);
		CacheUtil.clear(USER_CACHE);
		CacheUtil.clear(DICT_CACHE);
		CacheUtil.clear(FLOW_CACHE);
		CacheUtil.clear(SYS_CACHE);
		CacheUtil.clear(PARAM_CACHE);
		CacheUtil.clear(RESOURCE_CACHE);
		CacheUtil.clear(MENU_CACHE);
		CacheUtil.clear(DICT_CACHE, Boolean.FALSE);
		CacheUtil.clear(MENU_CACHE, Boolean.FALSE);
		CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
		CacheUtil.clear(PARAM_CACHE, Boolean.FALSE);
		return R.success(SystemConstant.DEFAULT_SUCCESS_MESSAGE);
	}
}
